package structures.sparsearray;

/**
 * 稀疏数组的应用
 */
public class SparseArrayDemo {
    public static void main(String[] args) {
        // 创建原始数组
        int[][] chessArray = new int[11][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        chessArray[4][5] = 2;
        // 输出原始数组
        System.out.println("");
        for (int[] row : chessArray) {
            for (int data : row) {
                System.out.print(data + "\t");
            }
            System.out.println();
        }

        // 将原始数组转换为稀疏数组
            // 1. 遍历出具体需要存储的数据数量
        int sum = 0;
        for (int[] row : chessArray) {
            for (int data : row) {
                if (data != 0) sum++;
            }
        }
        System.out.println("--------------------------");

            // 2. 创建数组 存储数据
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = chessArray.length;
        sparseArray[0][1] = chessArray[0].length;
        sparseArray[0][2] = sum;

        int count = 1;
        for (int row = 0; row < chessArray.length; row++) {
            for (int col = 0; col < chessArray[row].length; col++) {
                if (chessArray[row][col] != 0) {
                    sparseArray[count][0] = row;
                    sparseArray[count][1] = col;
                    sparseArray[count][2] = chessArray[row][col];
                    count++;
                }
            }
        }
            // 3. 读取数据
        for (int[] row : sparseArray) {
            for (int data : row) {
                System.out.print(data + "\t");
            }
            System.out.println();
        }
        System.out.println("--------------------------");

        // 还原数据
        int[][] chessArray2 = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int index = 1; index < sparseArray[0][2] + 1; index++) {
            chessArray2[sparseArray[index][0]][sparseArray[index][1]] = sparseArray[index][2];
        }

        for (int[] row : chessArray2) {
            for (int data : row) {
                System.out.print(data + "\t");
            }
            System.out.println();
        }
    }
}
